package main

import (
	"pro-downloader/app/controller"
	"pro-downloader/app/socket"
	"pro-downloader/assets"
	"github.com/gin-gonic/gin"
	"golang.org/x/sync/errgroup"
	"log"
	"net/http"
	"strings"
	"time"
)

var (
	g errgroup.Group
)

func main() {
	log.Println("==释放静态资源目录=============>>>>>>>>")
	dirs := []string{"static", "public"}//释放的目录
	for _, dir := range dirs {
		// 解压dir目录到当前目录
		if err := assets.RestoreAssets("./", dir); err != nil {
			log.Println("解压目录报错:",err)
			break
		}
	}

	httpServe := &http.Server{
		Addr:":80",
		Handler: httpServe(),
		ReadTimeout:5*time.Second,
		WriteTimeout:10*time.Second,
	}
	websocketServe := &http.Server{
		Addr:":3000",
		Handler: websocketServe(),
		ReadTimeout:5*time.Second,
		WriteTimeout:10*time.Second,
	}

	log.Println("==开启Web服务==========>>>>>>>>>>>")
	g.Go(func() error {
		return httpServe.ListenAndServe()
	})

	log.Println("==开启websocket服务========>>>>>>>>>>>")
	g.Go(func() error {
		return websocketServe.ListenAndServe()
	})

	if err := g.Wait(); err != nil {
		log.Fatal("启动服务器报错:%v",err)
	}

}

func CheckToken() gin.HandlerFunc  {
	return func(context *gin.Context) {
		//header := context.Request.Header
		//fmt.Println(header["Accept"])
	}
}

func AuthMiddleWare() gin.HandlerFunc  {
	return func(context *gin.Context) {
		url := context.Request.URL.String()

		//fmt.Println("Host：:", context.Request.Host)
		//fmt.Println("当前URL:", url)

		//判断登录信息
		if cookie, err := context.Request.Cookie("simon_token"); err == nil {
			value := cookie.Value
			//fmt.Println("获取到的Cookie：", value)
			if value == "simon" {
				//如果cookie存在simon ，则跳出该函数，继续向下执行
				context.Next()
				return
			}
		}

		//以下URL地址 不做拦截
		if url == "/login" || url == "/loginDo" || strings.HasPrefix(url,"/static"){
			context.Next()
			return
		}

		//拦截跳转到登录界面
		context.Redirect(http.StatusTemporaryRedirect, "/login")
		//在中间件中当验证用户异常时无法通过return 的方式终止业务代码运行， 需要通过 c.Abort 进行终止
		context.Abort()
		return
	}
}


func httpServe() http.Handler {
	router := gin.New()
	router.Use(gin.Recovery())
	router.Use(AuthMiddleWare())
	//router.Use(CheckToken())
	//设置加载模版文件
	router.LoadHTMLGlob("./static/views/*")
	//设置文件资源地址
	router.StaticFS("/public", http.Dir("./public"))

	//设置静态资源
	router.Static("/static","./static/res")
	//这种方式 打包了static 静态资源
	//router.StaticFS("/public", &assetfs.AssetFS{
	//	Asset:     assets.Asset,
	//	AssetDir:  assets.AssetDir,
	//	AssetInfo: assets.AssetInfo,
	//})

	//url地址请求
	router.GET("/", controller.Index)
	router.GET("/login", controller.Login)
	router.POST("/loginDo", controller.LoginDo)
	router.GET("/exit", controller.Exit)
	router.GET("/showAddTaskPanel", controller.TaskAddShow)
	router.POST("/taskadd", controller.TaskAdd)
	router.GET("/taskList", controller.TaskList)
	router.GET("/taskDel/:id", controller.TaskDel)
	router.GET("/Test", controller.Test)

	return router
}

func websocketServe() http.Handler {
	router := gin.New()
	router.Use(gin.Recovery())
	router.GET("/getDownloadProcss", socket.DownloadInfo)

	return router
}